<template>
  <el-page-header @back="router.go(-1)" title="返回">
    <template #content>
      <span>{{foodForm.id ? '编辑':'添加'}}书籍</span>
    </template>
  </el-page-header>

  <div class="content">
    <el-form ref="foodFormRef" :model="foodForm" :rules="foodFormRule" :inline="false" label-width="160px">

      <el-form-item label="名称" prop="bookName">
        <el-input v-model="foodForm.bookName" placeholder="请输入书籍名称" maxlength="20"/>
      </el-form-item>

      <el-form-item label="版本" prop="categoryId">
        <el-select style="width:200px" v-model="foodForm.categoryId" placeholder="请选择版本">
          <el-option v-for="(item, index) in categoryList" :key="index" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>

      
      

      <el-form-item label="书籍图片:" prop="image">

        <el-upload
            class="avatar-uploader"
            action="http://localhost:8081/file/upload"
            :headers="{token:token}"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
          <img v-if="foodForm.photo" :src="foodForm.photo" style="width:178px;height:178px;" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>

      <el-form-item label="描述">
        <el-input v-model="foodForm.description" type="textarea" />
      </el-form-item>

      <el-form-item>
        <el-button @click="handleSave">保存</el-button>
        <el-button type="primary" @click="handleCancle">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { reactive, ref } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { saveBook, findById } from "@/api/book";
import { getCategoryList } from "@/api/category";

import { ElMessage } from 'element-plus';

const router = useRouter();
const route = useRoute();

let categoryList = reactive([]);

let foodFormRef = reactive(null);
let foodForm = reactive({
  id: null,
  bookName: null,
  categoryId: null,
  photo: null,
  description: null,
});
let foodFormRule = reactive({
  bookName: [
    { required: true, trigger: 'blur',message: '请输入书名' }
  ],
 
  categoryId: [
    { required: true, trigger: 'blur',message: '请选择书籍版本' }
  ]
});

const token = sessionStorage.getItem("token");



// 加载版本信息
getCategoryList().then(resp => {
  categoryList.push(...resp.data);
});


  

if (route.query.bookId) {
  // 根据id查找
  findById(route.query.bookId).then(resp => {
    let food = resp.data;
    console.log(resp.data);
    foodForm.id = food.id;
    foodForm.bookName = food.bookName;
    foodForm.categoryId = food.categoryId;
    foodForm.photo = food.photo;
    foodForm.description = food.description;

    
  }).catch(error => {
    // 错误处理
  });
}

// 图片上传相关方法
const handleAvatarSuccess = (resp, file) => {
  foodForm.photo = resp.data;
};

const beforeAvatarUpload = file => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isJPG) {
    ElMessage.error('上传头像图片只能是 JPG 或 PNG 格式!');
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!');
  }
  return isJPG && isLt2M;
};

const handleSave = () => {
  // 判断是否校验通过
  foodFormRef.validate(valid => {
    if (valid) {

      
      saveBook(foodForm.id, foodForm).then(resp => {
        // 提示并且返回列表
        router.push({ path: '/book/list' });
      });
    }
  });
};
</script>



            
<style scoped>
.content {
  margin-top: 40px;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>